package com.olc.railing.base;

import android.Manifest;
import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.google.gson.Gson;
import com.olc.railing.BuildConfig;
import com.olc.railing.R;
import com.olc.railing.busniess.DataBusiness;
import com.olc.railing.busniess.LampControler;
import com.olc.railing.camera.CameraActivity;
import com.olc.railing.camera.VedioActivity;
import com.olc.railing.constant.Constants;
import com.olc.railing.http.GasCallBack;
import com.olc.railing.http.WrapperNetBusiness;
import com.olc.railing.listener.OnPayListener;
import com.olc.railing.model.BillInfo;
import com.olc.railing.model.ConfigInfo;
import com.olc.railing.model.GasOrderInfo;
import com.olc.railing.model.PayStatus;
import com.olc.railing.model.UserInfo;

import com.olc.railing.orm.BillInfoDao;
import com.olc.railing.orm.UserInfoDao;
import com.olc.railing.socket.Callback;
import com.olc.railing.socket.SocketClient;
import com.olc.railing.ui.MainActivity;
import com.olc.railing.utils.CommUtils;
import com.olc.railing.utils.MyLog;
import com.olc.railing.utils.SharedUtils;
import com.olc.railing.utils.ShellUtils;
import com.olc.railing.utils.TimeUtils;
import com.tyxh.paylibrary.bean.GasTradeInfoBody;
import com.tyxh.paylibrary.exception.BaseException;
import com.tyxh.paylibrary.exception.MyErrorException;
import com.tyxh.paylibrary.exception.NetNotAvailableException;
import com.tyxh.paylibrary.exception.NullException;
import com.tyxh.paylibrary.exception.ObuException;
import com.tyxh.paylibrary.listener.EtcCallBack;
import com.tyxh.paylibrary.model.ETCPay;
import com.tyxh.paylibrary.model.ETCPaySceneFactory;
import com.tyxh.paylibrary.model.GasPayBusiness;
import com.tyxh.paylibrary.model.MyExceptionType;
import com.tyxh.paylibrary.model.SceneType;
import com.tyxh.paylibrary.utils.ComonUtils;
import com.tyxh.paylibrary.utils.LogUtils;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;

import java.net.URL;
import java.net.URLConnection;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import butterknife.ButterKnife;


public abstract class BaseActivity extends AppCompatActivity {
    private static final String TAG = "BaseActivity";
    public static boolean isOpenGreen;
    public static boolean isOpenRed;

    public static String plateNo;
    public static boolean isPaySuccess;
    public static MediaPlayer mMediaPlayer;
    public static boolean isRecogisePlate;
    private static final int SLEEP_TIME = 450;
    private static Handler handler = new Handler();
    //当前支付状态
    public PayStatus payStatus = PayStatus.NO_PAY;

    public static boolean isFinishVideoAc;
    public static boolean isOpenVideoAc;
    public static String ocrVehPlateNo;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(getLayoutResId());
        ButterKnife.bind(this);
        init();

        //删除多余日志，只保留指定天数
        new Thread() {
            @Override
            public void run() {
                super.run();
                MyLog.delLogFile();
            }
        }.start();
    }

    public void initLamp() {
        MyLog.d(MyLog.TAG, "initLamp.....");
        new Thread(new RedLampRunnable()).start();
        new Thread(new GreenLampRunnable()).start();
    }

    private class RedLampRunnable implements Runnable {

        @Override
        public void run() {
            while (true) {

                if (isOpenRed) {
                    //  Log.e(TAG, "isOpenRed: " + isOpenRed);
                    try {
                        LampControler.closeRedLamp();
                        Thread.sleep(SLEEP_TIME);
                        LampControler.openRedLamp();
                        Thread.sleep(SLEEP_TIME);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    private class GreenLampRunnable implements Runnable {
        @Override
        public void run() {
            while (true) {
                if (isOpenGreen) {
                    //   Log.e(TAG, "isOpenGreen: " + isOpenGreen);
                    try {
                        LampControler.closeGreenLamp();
                        Thread.sleep(SLEEP_TIME);
                        LampControler.openGreenLamp();
                        Thread.sleep(SLEEP_TIME);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    /**
     * 获取布局文件
     *
     * @return
     */
    public abstract int getLayoutResId();

    protected abstract void init();



    /**
     * 播放音乐
     *
     * @param rid
     */
    public void playMedia(final int rid) {
//        if (BuildConfig.isRDA) {
//            writeMediaState(49);
//        }
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                try {
                    if (mMediaPlayer != null) {
                        mMediaPlayer.stop();
                        mMediaPlayer.reset();
                        mMediaPlayer.release();
                        mMediaPlayer = null;
                    }
                    mMediaPlayer = MediaPlayer.create(getApplicationContext(), rid);
                 //   MyLog.d(MyLog.TAG, "playMedia  mMediaPlayer " + mMediaPlayer);
                    if (mMediaPlayer == null) {
                        return;
                    }
                    mMediaPlayer.start();
                } catch (Exception e) {
                    MyLog.d(MyLog.TAG, "playMedia  mMediaPlayer " + e.getMessage());
                    e.printStackTrace();
                }
            }
        });
    }


    public void playMedia(final int[] rids, final int i) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                try {
                    if (mMediaPlayer != null) {
                        mMediaPlayer.stop();
                        mMediaPlayer.reset();
                        mMediaPlayer.release();
                        mMediaPlayer = null;
                    }
                    mMediaPlayer = MediaPlayer.create(getApplicationContext(), rids[i]);
                    mMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                        @Override
                        public void onCompletion(MediaPlayer mp) {
                            if (i + 1 < rids.length) {
                                playMedia(rids, i + 1);
                            }
                        }
                    });
                    mMediaPlayer.start();

                } catch (Exception e) {
                    MyLog.d(MyLog.TAG, "Exception " + e.toString());
                    e.printStackTrace();
                }
            }
        });
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        MyLog.e(MyLog.TAG, "keyCode: " + keyCode);
        switch (keyCode) {
            // 音量减小
            case KeyEvent.KEYCODE_VOLUME_DOWN://蓝色 25 扣费
                if (!isFastClick()) {
                    startPay();
                }
                return true;
            // 音量增大
            case KeyEvent.KEYCODE_VOLUME_UP://红灯 24 车牌识别
                if (!isFastClick()) {
                    if (BaseApplication.isFristRecogisePlate) {
                        BaseApplication.isFristRecogisePlate = false;
                        MyLog.d(MyLog.TAG, "startRecognisePlate..... ");
                        isRecogisePlate = true;
                        startOcr();
                    } else {
                        restartRecogisePlateOrEndOil();
                    }
                }
                return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * 按下绿灯开始支付
     */

    protected void startPay() {
        MyLog.e(MyLog.TAG, "startPay.........payStatus " + payStatus.code);
        if (isActivityTop(MainActivity.class, this) || isActivityTop(CameraActivity.class, this)) {
            playMedia(R.raw.no_recognise_vheplate_no);
            return;
        }
        if (isActivityTop(VedioActivity.class, this)) {
            if (payStatus != PayStatus.PAYING) {
                isOpenGreen = true;//绿灯闪烁
                // etcPay(new GasOrderInfo());
                payStatus = PayStatus.PAYING;
                fetchOrder();
            } else {
                //  MyLog.d(MyLog.TAG,"startPay.........payStatus "+payStatus.code);
                playMedia(R.raw.paying);
            }
        }

    }

    /**
     * 判断某activity是否处于栈顶
     *
     * @return true在栈顶 false不在栈顶
     */
    public boolean isActivityTop(Class cls, Context context) {
        ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        String name = manager.getRunningTasks(1).get(0).topActivity.getClassName();
        return name.equals(cls.getName());
    }

    protected void fetchOrder() {

    }


    /**
     * 结束加油
     */
    public void endOil() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                MyLog.d(MyLog.TAG, "手动结束加油.... ");
                if (isOpenRed) {//结束红灯闪烁
                    isOpenRed = false;
                }
                if (isOpenGreen) {
                    isOpenGreen = false;
                }
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                LampControler.closeGreenLamp();
                LampControler.closeRedLamp();
                LampControler.closeBuguangLamp();
            }
        }).start();

    }

    /**
     * 重新识别车牌或者结束加油
     */
    public void restartRecogisePlateOrEndOil() {
        MyLog.d(MyLog.TAG, "BaseActivity closeRecognise ");
        if (payStatus == PayStatus.PAYING) {
            playMedia(R.raw.paying);
            return;
        }
        if (!isPaySuccess) {
            BaseApplication.isFristRecogisePlate = true;
            endOil();
        } else {
            BaseApplication.isFristRecogisePlate = false;
            isPaySuccess = false;
            startOcr();
        }
    }


    /**
     * 开始识别车牌
     */
    public void startOcr() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                LampControler.openBuguangLamp();
                LampControler.openRedLamp();
                LampControler.closeGreenLamp();
            }
        }).start();

    }


    // 两次点击间隔不能少于指定的时间
    private static final int FAST_CLICK_DELAY_TIME = 2000;
    private static long lastClickTime;

    public static boolean isFastClick() {
        boolean flag = true;
        long currentClickTime = System.currentTimeMillis();
        if ((currentClickTime - lastClickTime) >= FAST_CLICK_DELAY_TIME) {
            flag = false;
        }
        lastClickTime = currentClickTime;
        return flag;
    }

    protected boolean isPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED
                    && checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
                    && checkSelfPermission(Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED
                    && checkSelfPermission(Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED) {
                return true;
            }
        } else {
            return true;
        }
        return false;
    }


    /**
     * 支付失败
     *
     * @param baseException
     */
    public void etcPaFial(BaseException baseException) {
        MyLog.d(MyLog.TAG, "etcPaFial "+baseException.getCode() + " " + baseException.getContent());
        UserInfo userInfo = new UserInfoDao(this).queryBySerialNo(SharedUtils.getSerialNo(this));
        if (userInfo != null) {
            GasOrderInfo gasOrderInfo = DataBusiness.getInstance(this).getmGasOrderInfo();
            userInfo.setCloseType(Constants.AUTO_CLOSE);//自动关闭
            userInfo.setEtcPayStatus(payStatus.code + "");
            userInfo.setOcrVehPlate(plateNo);
            userInfo.setAdress(GasPayBusiness.getInstance().getGasStationName());
            userInfo.setPrePrice(gasOrderInfo.getTotalMoney());
            userInfo.setDiscountPrice(gasOrderInfo.getTotalMoney() - gasOrderInfo.getPayMoney());
            userInfo.setActualPrice(gasOrderInfo.getPayMoney());
            userInfo.setOilGunNo(SharedUtils.getOilGunNo(BaseApplication.getApplication()));
            userInfo.setOilLiter(gasOrderInfo.getLitter() + gasOrderInfo.getUnit());
            userInfo.setUnitPrice(CommUtils.divide(String.valueOf(gasOrderInfo.getUnitPrice()), "100", 2));
            userInfo.setOilType(gasOrderInfo.getGoodsName());
            userInfo.setOperator(gasOrderInfo.getWorkNum());
            userInfo.setTradeNo(gasOrderInfo.getOtherOrderId());
            userInfo.setTradeTime(TimeUtils.getTime("yyyy/MM/dd HH:mm", System.currentTimeMillis() + ""));
            new UserInfoDao(BaseApplication.getApplication()).update(userInfo);
            if (socketClient != null) {
                socketClient.sendStrData(new Gson().toJson(userInfo));
            }
        }

        if (baseException instanceof ObuException) {
            playMedia(new int[]{R.raw.search_obu_fail}, 0);
        } else if (baseException instanceof MyErrorException) {
            dealMyError(baseException);
        } else if (baseException instanceof NetNotAvailableException) {
            playMedia(new int[]{R.raw.no_network}, 0);
        } else if (baseException instanceof NullException) {
            playMedia(new int[]{R.raw.tradefail}, 0);//待优化
        }
    }


    private void dealMyError(BaseException baseException) {
        int code = baseException.getCode();
        if (code == MyExceptionType.COMPARE_PLATE_FAIL.code) {
            playMedia(new int[]{R.raw.vehile_plate_compare_fail}, 0);
        } else if (code == MyExceptionType.ADD_BLACK_BILL.code) {
            playMedia(new int[]{R.raw.card_no_consume}, 0);
        } else if (code == MyExceptionType.DECRYPT_VEHICLE_FAIL.code) {
            playMedia(new int[]{R.raw.decy_car_info_fail}, 0);
        } else if (code == MyExceptionType.WRITE_CARD_INNIT_FAIL.code
                || code == MyExceptionType.WRITE_0019_FAIL.code
                || code == MyExceptionType.READ_0019_FAIL.code
                || code == MyExceptionType.WRITE_CARD_CONSUME_FAIL.code
                || code == MyExceptionType.CARD_BALANCE_ERROR.code) {
            playMedia(new int[]{R.raw.tradefail}, 0);
        } else if (code == MyExceptionType.SERVER_EXCEPTION.code
                || code == MyExceptionType.HTTP_EXCEPTION.code) {
            playMedia(new int[]{R.raw.service_exception}, 0);
        }
    }


    /**
     * 检查网络是否可用
     */
    public boolean isNetworkAvailable() {
        ConnectivityManager mConnectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
        if (mNetworkInfo != null) {
            return mNetworkInfo.isAvailable();
        }
        return false;
    }


    private final static int receivePort = 5000;
    public static DatagramSocket clientSocket;
    public static SocketClient socketClient;
    private boolean isEnd;//是否获取到大屏ip

    /**
     * 获取大屏局域网ip地址并且建立连接
     */
    public void configIpToScreen() {
        try {
            clientSocket = new DatagramSocket(20000);
        } catch (SocketException e) {
            e.printStackTrace();
        }
        new Thread(new MyRunnable()).start();
        isEnd = false;
        sendUdpMessage();
    }

    private void sendUdpMessage() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                int times = 0;
                while (!isEnd) {
                    try {
                        byte[] bytes = "DP0001FIND".getBytes();
                        DatagramPacket datagramPacket = new DatagramPacket(bytes, bytes.length, InetAddress.getByName("255.255.255.255"), 9100);
                        clientSocket.send(datagramPacket);
                        Thread.sleep(2000);
                    } catch (Exception localException) {
                        localException.printStackTrace();
                        Log.d("sendUdpMessage", "ip error" + localException.toString());
                    }
                    times++;
                    // MyLog.d(MyLog.TAG, "times " + times);
                }
            }
        }).start();
    }


    public class MyRunnable implements Runnable {

        @Override
        public void run() {
            try {
                while (true) {
                    MyLog.d(MyLog.TAG, "等待大屏。。。。。。。 ");
                    byte[] bytes = new byte[128];
                    DatagramPacket datagramPacket = new DatagramPacket(bytes, bytes.length);
                    clientSocket.receive(datagramPacket);
                    String datas = new String(datagramPacket.getData(), datagramPacket.getOffset(), datagramPacket.getLength());
                    MyLog.d(MyLog.TAG, "data: " + datas);
                    if (!datas.equals("DP0001FIND")) {
                        isEnd = true;
                        startSocketClinet(datas);

                    }
                }
            } catch (Exception exception) {
                exception.printStackTrace();
            }
        }
    }

    public void startSocketClinet(String ip) {
        // MyLog.d(TAG, "startSocketClinet: ip " + ip);
        if (socketClient == null) {

            socketClient = new SocketClient(ip, 8918, new Callback<String>() {
                @Override
                public void call(String s) {
                    MyLog.d(MyLog.TAG, "call " + s);
                    notifyConnectedBigScreen();
                }

                @Override
                public void onConnectSucces(String host) {
                    MyLog.d(MyLog.TAG, "onConnectSucces " + host);
                    playMedia(R.raw.big_screen_connected);
                }

                @Override
                public void onConnectFail(Exception e) {
                    MyLog.d(MyLog.TAG, "onConnectFail " + e.toString());
                }

            });
        }
    }

    public void notifyConnectedBigScreen() {

    }


    protected void initEtcPay(ConfigInfo configInfo) {
        ETCPay etcPay = new ETCPay.ETCBuilder(this, configInfo.getAppKey())// a9df31445991e40e523bf8807de6a545
                .setPathName("/dev/ttyZC2")//ttyMT0  ttyZC2  ec0d2ce13e1744fabb9551db68353e0b
                .setBaudrate(115200)
                .setRsuId(configInfo.getRsu_id())
                .setSceneId(configInfo.getGas_id())//停车场 6120000004 //加油站 610050125024  //测试610300000001   610050125024
                .setStationName(configInfo.getGas_name())
                .setDevNumber(CommUtils.getDeviceSN())// TY202109081645067381  TY202108301936075736
                .setCropId(configInfo.getOperator_id())
                .setDevType(Constants.DEV_TYPE)
                .setDebug(true)
                .setTagName("railing_log")
                .setTxPower(15)
                .build();
        //StopTerminal  a9df31445991e40e523bf8807de6a545


        new ETCPaySceneFactory().generatePayType(SceneType.GAS);
        GasPayBusiness.getInstance().initSDK(etcPay);
    }


}
